using System;

namespace FileMapper {
    public class Extent: IComparable<Extent> {
        public long? Offset { get; set; }
        public long Size { get; set; }

        public long? End {
            get {
                if (Offset == null) {
                    return null;
                } else {
                    return (long)(Offset) + Size;
                }
            }
        }

        public Extent() {}

        public override bool Equals(object obj) {
            var ext = obj as Extent;
            if (ext == null) {
                return false;
            }
            return Offset.Equals(ext.Offset) && Size.Equals(ext.Size);
        }

        public override int GetHashCode() {
            return Offset.GetHashCode() ^ Size.GetHashCode();
        }

        public override string ToString() {
            return string.Format("[Extent: Offset={0}, Size={1}, End={2}]", Offset, Size, End);
        }

        public int CompareTo(Extent other) {
            return ((long)(Offset)).CompareTo((long)(other.Offset));
        }

        public bool Contains(long? position) {
            return Offset != null && position != null && (long)(Offset) <= position && position < (long)(End);
        }

        public bool Overlaps(Extent extent) {
            return Contains(extent.Offset) || extent.Contains(Offset);
        }
    }
}
